package com.aishuang.gateway.filter;

import com.alibaba.nacos.common.model.RestResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Title: AuthorizeFilter
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/3/8 9:33
 */
@Component
@Order(-1)  // 最先进入当前这个过滤器
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求头信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token"); // 获取请求头的token
        if(StringUtils.hasText(token)) {
            // 获取参数信息
            MultiValueMap<String, String> queryParams = request.getQueryParams();
            String username = queryParams.getFirst("username");
            String password = queryParams.getFirst("password");
            if("admin".equals(username) && password.equals("123")) {
                // 放行
                return chain.filter(exchange);
            }

        }

        DataBufferFactory bufferFactory = response.bufferFactory();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            final DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(new RestResult<>(403, "拒绝访问")));
            return response.writeWith(Mono.fromSupplier(() -> wrap));
        } catch (JsonProcessingException e) {

        }

        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();


//        response.setStatusCode(HttpStatus.FORBIDDEN);
//        return response.setComplete(); // 响应
    }
}
